<?php

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Api\Traits\ProxyTrait;
use App\Models\AdminUser;
use App\Models\User;
use App\Models\PlayerUser;
use App\Models\Apply;
use App\Models\ApplyHasPlayer;
use App\Models\Drawlot;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Log;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use App\Models\League;
use App\Models\Cup;

class MobileController extends ApiController
{
    use AuthenticatesUsers, ProxyTrait;


    public function __construct()
    {
        
    }

    /**
     * 获取用户token状态
     *
     * @return string
     */
    public function playerStatus(Request $request)
    {
        Log::info('playerInfo request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            return $this->success(['token' => 'ok']);
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /**
     * 获取player信息
     *
     * @return string
     */
    public function playerInfo(Request $request)
    {
        Log::info('playerInfo request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            $role_name[] = [];
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            //if( !empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    $return = $user->playerUser->toArray();
                    Log::info($user->roles);
                    foreach ($user->roles as $role) {
                        $return['roles'][] = $role['name'];
                    }
                    $league = League::where('id', $user->playerUser->league_id)->first();
                    $cup = Cup::where('id', $user->playerUser->cup_id)->first();
                    if(!empty($league)){
                        $return['league_show'] = $league->name;
                    }else{
                        $return['league_show'] = '';
                    }
                    if(!empty($cup)){
                        $return['cup_show'] = $cup->name;
                    }else{
                        $return['cup_show'] = '';
                    }
                    return $this->success(['playeruser' => $return , 'role' => $role_name]);
                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            /*}else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }*/
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /**
     * 新用户注册信息
     *
     * @return string
     */
    public function playerRegister(Request $request)
    {
        Log::info('playerRegister request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        Log::info($user);
        if($user){
            //存储用户register的信息
            Log::info('-----------register------------------');
            Log::info($request->user_id);
            Log::info($request->name);
            Log::info($request->mobile);
            Log::info($request->age);
            Log::info($request->height);
            Log::info($request->weight);
            Log::info($request->site);
            $player_user = PlayerUser::firstOrNew(['user_id' => $request->user_id]);
            $player_user->realname = $request->name;
            $player_user->age = $request->age;
            $player_user->height = $request->height;
            $player_user->weight = $request->weight;
            $player_user->site = $request->site;
            $player_user->save();

            $user->phone = $request->mobile;
            $user->save();

            return $this->message('注册成功！');
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /**
     * 获取可报名信息
     *
     * @return string
     */
    public function applyInfo(Request $request)
    {
        Log::info('applyInfo request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            if( !empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    //todo 得到该球员能够报名的比赛
                    log::info($user->playerUser->league_id);
                    log::info($user->playerUser->cup_id);
                    $league_id = $user->playerUser->league_id;
                    $cup_id = $user->playerUser->cup_id;
                    //Log::info(date("Y-m-d H:i:s",time()));
                    $current_time = date("Y-m-d H:i:s",time());
                    //Log::info(gettype($current_time));
                    /*if(is_string($current_time)){
                        Log::info('hgahahahha');
                    }*/
                    Log::info($current_time);
                    $appy = Apply::where('end_time', '>', $current_time)
                                ->where('enable', '=', 'F')
                                ->where(function ($query) use ($league_id, $cup_id) {
                                    $query->where('league_id', '=', $league_id)
                                        ->orWhere('cup_id', '=', $cup_id);
                                })->get();
                    return $this->success(['apply' => $appy]);
                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            }else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /**
     * 报名
     *
     * @return string
     */
    public function applyJoin(Request $request)
    {
        Log::info('applyJoin request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            if(!empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    //todo player报名写入报名表
                    Log::info($user->id);
                    Log::info($request->applyId);
                    if($request->applyId!=0){
                        $joinPlayer = ApplyHasPlayer::firstOrNew([
                              'apply_id' => $request->applyId,
                              'user_id' => $user->id,
                          ]);
                        $joinPlayer->user_level = $user->playerUser->level;
                        $joinPlayer->save();
                        return $this->success(['joinPlayer' => $joinPlayer]);
                    }
                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            }else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /**
     * 获取报名球员信息
     *
     * @return string
     */
    public function applyPlayer(Request $request)
    {
        Log::info('applyPlayer request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            if(!empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    //todo 获取当前报名队员信息
                    Log::info($request->applyId);
                    if($request->applyId!=0){
                        $applyHasPlayer = ApplyHasPlayer::with('user')->where('apply_id', '=', $request->applyId)->get();
                        log::info($applyHasPlayer);
                        return $this->success(['applyHasPlayer' => $applyHasPlayer]);
                    }
                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            }else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /**
     * 获取可抽签比赛
     *
     * @return string
     */
    public function drawlotInfo(Request $request)
    {
        Log::info('drawlotInfo request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            if( !empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    //todo 得到该球员能够抽签的比赛
                    log::info($user->playerUser->league_id);
                    log::info($user->playerUser->cup_id);
                    $league_id = $user->playerUser->league_id;
                    $cup_id = $user->playerUser->cup_id;
                    //Log::info(date("Y-m-d H:i:s",time()));
                    $current_time = date("Y-m-d H:i:s",time());
                    //Log::info(gettype($current_time));
                    /*if(is_string($current_time)){
                        Log::info('hgahahahha');
                    }*/
                    Log::info($current_time);
                    $applys = Apply::where('end_time', '>', $current_time)
                                ->where('enable', '=', 'T')
                                ->where(function ($query) use ($league_id, $cup_id) {
                                    $query->where('league_id', '=', $league_id)
                                        ->orWhere('cup_id', '=', $cup_id);
                                })->get();
                    $drawlot = [];
                    foreach ($applys as $apply) {
                        Log::info($apply->id);
                        $applyHasPlayer = ApplyHasPlayer::where('user_id', '=', $user->id)
                                                        ->where('apply_id', '=', $apply->id)
                                                        ->first();
                        if(!empty($applyHasPlayer)){
                            array_push($drawlot, $apply);
                        }
                    }
                    return $this->success(['drawlot' => $drawlot]);
                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            }else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /** 抽签
        applyId
        user_level 用户所在档
        round 第几场比赛
    */
    public function drawlotResult(Request $request)
    {
        Log::info('drawlotResult request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            if( !empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    //todo 抽签接口
                    //首先查看apply的enable
                    Log::info($request->applyId);
                    if($request->applyId!=0){
                        $apply = Apply::where('id', '=', $request->applyId)->first();
                        log::info($apply->id);
                        log::info($apply->referee);
                        log::info($apply->referee_level);
                        log::info($apply->group);
                        log::info($user->id);
                        if($apply && $apply->is_drawlot == 'T'){
                            return response()->json(['status' => 'fail', 'code' => '996', 'message' =>'其他球员抽签中，请轮询']);
                        }else{
                            $drawlot_user = Drawlot::where('apply_id', '=', $request->applyId)
                                    ->where('round', '=', $request->round)
                                    ->where('user_id', '=', $user->id)
                                    ->first();
                            if(!empty($drawlot_user->group)){
                                log::info($drawlot_user->group);
                                return response()->json(['status' => 'fail', 'code' => '995', 'group' => $drawlot_user->group, 'message' =>'已经抽签过了']);
                            }else{
                                $apply->is_drawlot = 'T';
                                $apply->save();
                                //开始抽签
                                //查找所在档位总的空位数
                                $drawlot_totle = Drawlot::where('apply_id', '=', $request->applyId)
                                        ->where('round', '=', $request->round)
                                        ->where('user_level', '=', $request->user_level)
                                        ->get();
                                $drawlot_totle_count = count($drawlot_totle);
                                log::info($drawlot_totle_count);

                                $rand_array = [];
                                //遍历组
                                for($i=1;$i<=$apply->group;$i++){
                                    $drawlot_group = Drawlot::where('apply_id', '=', $request->applyId)
                                        ->where('round', '=', $request->round)
                                        ->where('user_level', '=', $request->user_level)
                                        ->where('group', '=', $i)
                                        ->get();
                                    //查找该档位下每个组的数量，看是否有空位，如果有放入随机数组
                                    $drawlot_group_count = count($drawlot_group);
                                    log::info($drawlot_group_count);
                                    $group_count = $drawlot_totle_count/$apply->group;
                                    log::info($group_count);
                                    if($drawlot_group_count < $group_count){
                                        array_push($rand_array, $i);
                                    }
                                }

                                //先看一下所在档是否出裁判并且裁判数不为0
                                if($request->user_level == $apply->referee_level && $apply->referee != 0){
                                    //查找一下当前档有几个裁判，是否还有裁判空位
                                    $drawlot_referee_group = Drawlot::where('apply_id', '=', $request->applyId)
                                        ->where('round', '=', $request->round)
                                        ->where('user_level', '=', $request->user_level)
                                        ->where('group', '=', 99)
                                        ->get();
                                    $drawlot_referee_group_count = count($drawlot_referee_group_count);
                                    log::info($drawlot_referee_group_count);
                                    //如果有裁判空位
                                    if($drawlot_referee_group_count < $apply->referee){
                                        //（还要查找其他几场是否有当裁判，如果有，不加入随机数组）
                                        $drawlot_is_referee = Drawlot::where('apply_id', '=', $request->applyId)
                                                            ->where('user_id', '=', $request->$user->id)
                                                            ->where('group', '=', 99)
                                                            ->get();
                                        //该用户当裁判的场次
                                        $drawlot_is_referee_count = count($drawlot_is_referee);
                                        log::info($drawlot_is_referee_count);
                                        if($drawlot_is_referee_count == 0){
                                            //没当过裁判，加入随机数组，参与随机，99为裁判
                                            array_push($rand_array, 99);
                                        }                   
                                    }
                                }
                                log::info($rand_array);
                                //要加入一个判断，如果查找几个分租都没有空位了，就要报错了，说明该档安排人员大于空位
                                if(empty($rand_array)){
                                    return response()->json(['status' => 'fail', 'code' => '994', 'message' =>'没有签位了']);
                                }
                                //随机出一个组
                                $drawlot_result = $rand_array[array_rand($rand_array,1)];
                                log::info($drawlot_result);
                                $drawlot_user->group = $drawlot_result;
                                $drawlot_user->save();

                                $apply->is_drawlot = 'F';
                                $apply->save();

                                return $this->success(['drawlot_result' => $drawlot_result]);
                            }   
                        }
                    }

                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            }else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }

    /** 抽签分组信息查看 四场比赛  ABC组 
        applyId
    */
    public function drawlotView(Request $request)
    {
        Log::info('drawlotResult request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志
        $header_authorization = $request->header('Authorization');
        Log::info($header_authorization);

        $user = User::where('weixin_session_key', $header_authorization)->first();
        if($user){
            foreach ($user->roles as $role) {
                Log::info($role);
                $role_name[] = $role['name'];
            }
            if( !empty($role_name) && in_array("player",$role_name)){
                if($user->playerUser){
                    //todo 抽签接口
                    //首先查看apply的enable
                    Log::info($request->applyId);
                    if($request->applyId!=0){
                        $apply = Apply::where('id', '=', $request->applyId)->first();
                        log::info($apply->id);
                        log::info($apply->group);
                        log::info($apply->round);
                        $drawlotView = [];
                        

                        for($i=0;$i<$apply->round;$i++){
                            $drawlotView_group = [];
                            //裁判组
                            $drawlot_referee_group = Drawlot::with('user')
                                        ->where('apply_id', '=', $request->applyId)
                                        ->where('round', '=', $i+1)
                                        ->where('group', '=', 99)
                                        ->get();
                            array_push($drawlotView_group, $drawlot_referee_group);
                            for($j=0;$j<$apply->group;$j++){
                                $drawlot_group = Drawlot::with('user')
                                        ->where('apply_id', '=', $request->applyId)
                                        ->where('round', '=', $i+1)
                                        ->where('group', '=', $j+1)
                                        ->get();
                                array_push($drawlotView_group, $drawlot_group);
                            }
                            array_push($drawlotView, $drawlotView_group);
                        }
                        log::info($drawlotView);
                        return $this->success(['drawlotView' => $drawlotView]);
                    }

                }else{
                    Log::info('wwwwwwwwwwwwwwww');
                    return response()->json(['status' => 'fail', 'code' => '999', 'message' =>'未设置球员信息']);
                }
            }else{
                Log::info('rrrrrrrrrrrrrr');
                return response()->json(['status' => 'fail', 'code' => '998', 'message' =>'不是player']);
            }
        }else{
            return response()->json(['status' => 'fail', 'code' => '997', 'message' =>'不存在的用户']);
        }
        
    }
}
